package se.com.movie.reader.reader;

import java.io.File;

import se.com.movie.reader.writer.MovieWriter;

public class MovieReader implements Reader {
	private static MovieReader mMovieReader = null;
	private Reader mLoadXMLSettings = null;
	private MovieWriter mMovieWriter;
	private Thread[] mThread = null;
	private File[] mRoots = null;
	private int mCurrentRoot = 0;
	private int MAX_THREADS = 4;
	private int mCurrentNrThreads = 0;

	private MovieReader() {
		mMovieWriter = MovieWriter.getInstance();
		mLoadXMLSettings = new LoadXMLSettings();
	}

	public static MovieReader getInstance() {
		if (mMovieReader == null) {
			mMovieReader = new MovieReader();
		}
		return mMovieReader;
	}

	@Override
	public void read() {
		mLoadXMLSettings.read();
		mRoots = File.listRoots();
		System.out.println("Total nr of disks: " + mRoots.length);
		mThread = new Thread[mRoots.length];
		int cont = 0;
		for (mCurrentRoot = 0; cont != -1 && mCurrentRoot < mRoots.length; ++mCurrentRoot) {
			mThread[mCurrentNrThreads] = new MovieReaderThread(mRoots[mCurrentRoot]);
			mThread[mCurrentNrThreads].start();
			cont = incretmentThreads();
		}
		join();
		mMovieWriter.setQuitWhenDone(true);
	}

	private void join() {
		int i = 0;
		do {
			boolean cont = false;
			if (mThread[i] != null && mThread[i].isAlive()) {
				System.out.println("Thread[" + i + "] is Active");
				try {
					mThread[i].join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					mThread[i] = null;
					cont = true;
				}
			} else {
				System.out.println("Thread[" + i + "] is not Active");
			}
			++i;
			if (i == MAX_THREADS && cont) {
				i = 0;
			}
		} while (i < MAX_THREADS);
	}

	public synchronized File incrementRoot() {
		if (mCurrentRoot < mRoots.length) {
			return mRoots[mCurrentRoot++];
		}
		return null;
	}

	public synchronized int incretmentThreads() {
		if (mCurrentNrThreads < MAX_THREADS) {
			return mCurrentNrThreads++;
		}
		return -1;
	}

	public int getRunningThreads() {
		int count = -1;
		if (mThread != null) {
			for (int i = 0; i < mThread.length; ++i) {
				if (mThread[i] != null) {
					if (!mThread[i].isAlive()) {
						mThread[i] = null;
						return i;
					}
				}
			}
		}
		return count;
	}

	public Thread[] getThread() {
		return mThread;
	}
}
